package com.archer.datasource;

import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class JdbcTemplateManger {

    private static final Map<String, JdbcTemplate> jdbcTemplateMap = new ConcurrentHashMap<>();

    /**
     * 取数据库连接
     *
     * @return
     */
    public synchronized static JdbcTemplate getJdbcTemplate() {
        JdbcTemplate jdbcTemplate = jdbcTemplateMap.get("sst");
        if (jdbcTemplate == null) {
            Properties ps = new Properties();

            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream("app-config/db.properties");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (fileInputStream != null) {
                try {
                    ps.load(fileInputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            ps.setProperty("driver", "com.mysql.jdbc.Driver");

            DBCPDataSourceFactory factory = new DBCPDataSourceFactory();
            factory.setProperties(ps);
            DataSource dataSource = factory.getDataSource();
            jdbcTemplate = new JdbcTemplate(dataSource, true);

            // 设置查询超时时间
            jdbcTemplate.setQueryTimeout(Integer.parseInt(ps.getProperty("queryTimeOut", "10")));

            jdbcTemplateMap.put("sst", jdbcTemplate);
        }
        return jdbcTemplate;
    }


}
